<?
/**
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
 * 02111-1307, USA.
 */

$line = $_GET['line'];
$date = $_GET['date'];

if (!$line) die(':(');

//echo "http://www.dan.co.il/search/lines_times.asp?LineNumber=$line-_&alltimes=1".($date?'Date2='.$date:'');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.dan.co.il/search/lines_times.asp?LineNumber=$line-_&alltimes=1".($date?'&Date2='.$date:''));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_exec($ch);
$s = curl_multi_getcontent($ch);
curl_close($ch);

$doc= new DOMDocument();
if(@!$doc->loadHTML($s))
{
   echo ("Error in document");
}

$xpath = new DOMXPath($doc);

// include only times and titles in the query
$query = "//*[@class='time']|//*[@class='pline']|//*[@class='plinered']|//*[@class='plineblue']";
$entries = $xpath->query($query);

$passed = 0;
$arr = array();

if ($entries->length==0) {
	header("HTTP/1.0 404 Not Found");
	$s = "";
} else {
	foreach ($entries as $item) {
		if (preg_match("/(\d\d:\d\d)|כל \d\d דקות|מכוון/", $item->nodeValue)) {
			$val = preg_replace('/:/','',$item->nodeValue);
	
			// check how many titles were passed
			if(!is_numeric($val) && $passed < 2) {
				$arr[$passed-1]['schedule'] = isset($temp)?$temp:'';unset($temp);
				$arr[$passed]['station']  = trim($val);
				$passed++;
			}
			else if(is_numeric($val) && $passed !=0 ) {
				$temp .= $val;
			}
			else if(!is_numeric($val) && $passed==2) {
				$arr[$passed-1]['schedule'] = isset($temp)?$temp:'';
				break;
			}
		}
	}
	$s="{$arr[0]['station']}\n{$arr[1]['station']}\n\n{$arr[0]['schedule']}\n{$arr[1]['schedule']}\n";
}

//$s = iconv("ISO-8859-8", "UTF-8", $s);
header('Content-Type: text/plain; charset=utf-8');
header('Content-Length: '.strlen($s));
echo $s;
?>
